package cn.gok.springsecuritydemo02.filter;

import cn.gok.springsecuritydemo02.exception.ValidateCodeException;
import cn.gok.springsecuritydemo02.handler.LoginFailHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
    自定义的验证码验证的过滤器
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

    @Autowired
    LoginFailHandler loginFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        try {

            //1、只是对登录请求，才有验证码验证, 同时请求方式为post
            if (request.getRequestURI().equals("/login") && request.getMethod().equals("POST")){
                //取出用户提交的验证码
                String imageCode = request.getParameter("imageCode");

                //取出缓存中的验证码
                String validateCode = (String) request.getSession().getAttribute("validateCode");


                if (imageCode == null || "".equals(imageCode)){
                    throw new ValidateCodeException("验证码不能为空");
                }

                if (validateCode == null){
                    throw new ValidateCodeException("验证码已失效");
                }

                if (!validateCode.equals(imageCode)){
                    throw new ValidateCodeException("验证码不正确");
                }

                //验证通过，删除session中的验证码
                request.getSession().removeAttribute("validateCode");

            }
            filterChain.doFilter(request,response);

        } catch(AuthenticationException e) {
            //使用自定义的登录失败处理器，统一响应验证失败信息
            loginFailHandler.onAuthenticationFailure(request, response, e);
        }
    }
}
